package com.shop.product.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shop.framework.util.Logger;
import com.shop.product.dao.ProductDAO;
import com.shop.product.vo.ProductVO;

@Service
public class ProductServiceImpl implements ProductService {

	@Autowired
	private ProductDAO dao;
	
	/**
	 * 상품 총 개수
	 * @param src_type
	 * @param src_keyword
	 * @return
	 */
	@Override
	public int getProductCount(String src_type, String src_keyword) {
		return dao.getProductCount(src_type, src_keyword);
	}

	/**
	 * 상품 리스트
	 * @param current_page
	 * @param src_type
	 * @param src_keyword
	 * @return
	 */
	public List<ProductVO.ProductItem> listProduct(int current_page,
													int list_row_no,
													String src_type,
													String src_keyword) {
		
		List<ProductVO.ProductItem> list = dao.listProduct(current_page, list_row_no, src_type, src_keyword);
		for (int i = 0 ; i < list.size(); i++) {
			list.get(i).addImg(dao.getMasterImg(list.get(i).getSeq()+""));
		}
		return list;
	}
	
	/**
	 * 상품등록
	 * 상품등록 후 상품의 키를 받아 태그와 옵션을 저장한다
	 * 상품등록후 파일을 저장한다
	 */
	@Override
	public void addProduct(ProductVO.ProductItem productItem) {
		String tags = "";
		// Tag
		if (productItem.getTag_name() != null) {
			for (int i = 0; i < productItem.getTag_name().length; i++) {
				
				tags += productItem.getTag_name()[i] + ",";
				Logger.getLogger().debug(productItem.getTag_name()[i]);
			}
			productItem.setTags(tags.substring(0, tags.length()-1));
		}
		 
		int productSeq = dao.addProduct(productItem);		
		
		// 상세 옵션 저장
		for (int i = 0; i < productItem.getOpt_master_seq().length; i++) {
			ProductVO.ProductOptDetail optVo = new ProductVO.ProductOptDetail();
			
			optVo.setAdmin_seq(1);
			optVo.setOpt_desc(productItem.getOpt_desc()[i]);
			optVo.setOpt_master_seq(Integer.parseInt(productItem.getOpt_master_seq()[i]));
			optVo.setProduct_seq(productSeq);
			
			dao.addOpt(optVo);
			
			Logger.getLogger().debug(productItem.getOpt_master_seq()[i]);
			Logger.getLogger().debug(productItem.getOpt_desc()[i]);
		}		
//		
//		// 이미지 저장
		for (int i = 0; i < productItem.getImg_path().length; i++) {
			ProductVO.ProductImg imgVo = new ProductVO.ProductImg();
			
			System.out.println(productItem.getImg_path()[i]);
			imgVo.setAdmin_seq(1);
			if (i > 0) {
				imgVo.setFlag("M");
			}
			imgVo.setImg_path(productItem.getImg_path()[i]);
			imgVo.setProduct_seq(productSeq);
			dao.addImg(imgVo);	
		}
	}
	
}
